package com.aigc.aigc.controller;

import com.aigc.aigc.utils.VivoAuth;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;


@RestController
@RequestMapping("/test")
public class TestController {


    @Autowired
    private RestTemplate restTemplate;

    //蓝心
    @GetMapping("/vivogpt")
    public String vivogpt(@RequestParam String prompt) throws Exception {
        String appId = "3032693269";
        String appKey = "pORdeLuUVXfBNIeY";
        String URI = "/vivogpt/completions";
        String DOMAIN = "api-ai.vivo.com.cn";
        String METHOD = "POST";
        UUID requestId = UUID.randomUUID();
        System.out.println("requestId: " + requestId);

        Map<String, Object> map = new HashMap<>();
        map.put("requestId", requestId.toString());
        String queryStr = mapToQueryString(map);

        // 构建请求体
        Map<String, String> data = new HashMap<>();
        data.put("prompt", prompt); // 替换原本的固定值
        data.put("model", "vivo-BlueLM-TB");
        UUID sessionId = UUID.randomUUID();
        data.put("sessionId", sessionId.toString());
        System.out.println(sessionId);

        HttpHeaders headers = VivoAuth.generateAuthHeaders(appId, appKey, METHOD, URI, queryStr);
        headers.add("Content-Type", "application/json");
        System.out.println(headers);
        String url = String.format("http://%s%s?%s", DOMAIN, URI, queryStr);
        String requestBodyString = new ObjectMapper().writeValueAsString(data);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE));
        httpHeaders.addAll(headers);
        return getString(url, requestBodyString, restTemplate, httpHeaders);
    }

    public String getString(String url, String requestBodyString, RestTemplate restTemplate, HttpHeaders httpHeaders) {
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBodyString, httpHeaders);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            System.out.println("Response body: " + response.getBody());
        } else {
            System.out.println("Error response: " + response.getStatusCode());
        }
        return response.getBody();
    }

    // 地理编码(POI搜索)
    @GetMapping("/geo")
    public String geo() throws UnsupportedEncodingException {
        final String appId = "3032693269";
        final String appKey = "pORdeLuUVXfBNIeY";
        final String method = "GET";
        final String domain = "lbs-api.vivo.com.cn";
        final String uri = "/search/geo";
        // 请求参数
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("keywords", "卓悦汇");
        queryMap.put("city", "深圳");
        queryMap.put("page_num", 1);
        queryMap.put("page_size", 3);
        // 将请求参数拼接成url查询字符串
        String query = mapToQueryString(queryMap);
        HttpHeaders headers = VivoAuth.generateAuthHeaders(appId, appKey, method, uri, query);
        String url = String.format("http://%s%s?%s", domain, uri, query);
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        ResponseEntity<String> resp = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
        System.out.printf("response status: %s%n", resp.getStatusCode());
        return resp.getBody();
    }

    @Autowired
    private ResourceLoader resourceLoader;

    //AI绘画   1. 提交作画任务
    @GetMapping("/task")
    public String task_submit() throws UnsupportedEncodingException {
        final String APP_ID = "3032693269";
        final String APP_KEY="pORdeLuUVXfBNIeY";
        final String METHOD = "POST";
        final String URI = "/api/v1/task_submit";
        final String DOMAIN = "api-ai.vivo.com.cn";

        // 定义请求体数据
        Map<String, Object> data = new HashMap<>();
        data.put("height", 768);
        data.put("width", 576);
        data.put("prompt", "一个穿着破旧的衣服的农民工正在大热天搬砖已经汗流浃背");
        data.put("styleConfig", "55c682d5eeca50d4806fd1cba3628781");
        // 将请求体数据转换为 JSON 格式
        String requestBody = JSON.toJSONString(data);
        // 请求参数
        Map<String, Object> query = new HashMap<>();
        String queryString = mapToQueryString(query);
        HttpHeaders headers = VivoAuth.generateAuthHeaders(APP_ID, APP_KEY, METHOD, URI, queryString);
        headers.add("Content-Type", "application/json");
        String url = String.format("http://%s%s", DOMAIN, URI);
        RestTemplate restTemplate = new RestTemplate();
        return getString(url, requestBody, restTemplate, headers);
    }
    //AI绘画  2.查询作画任务
    @GetMapping("/taskProgress")
    public String taskProgress() throws UnsupportedEncodingException {
        final String APP_ID =  "3032693269";
        final String APP_KEY ="pORdeLuUVXfBNIeY";
        final String METHOD = "GET";
        final String URI = "/api/v1/task_progress";
        final String DOMAIN = "api-ai.vivo.com.cn";

        //请求url参数
        Map<String, Object> data = new HashMap<>();
        data.put("task_id","fb16d23843175f7f8c676ec14b502867");
        String queryString = mapToQueryString(data);
        HttpHeaders headers = VivoAuth.generateAuthHeaders(APP_ID, APP_KEY, METHOD, URI, queryString);
        String url = String.format("https://%s%s?%s", DOMAIN, URI,queryString);
        headers.add("Content-Type", "application/json");
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<Object> requestEntity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            System.out.println("Response body: " + response.getBody());
        } else {
            System.out.println("Error response: " + response.getStatusCode());
        }
        return response.getBody();


    }
    // 3.AI绘画 取消绘画任务
    @GetMapping("/taskCancel")
    public String taskCancel() throws UnsupportedEncodingException {
        final String APP_ID =  "3032693269";
        final String APP_KEY ="pORdeLuUVXfBNIeY";
        final String METHOD = "POST";
        final String URI = "/api/v1/task_cancel";
        final String DOMAIN = "api-ai.vivo.com.cn";

        //请求url参数
        Map<String, Object> queryData = new HashMap<>();
        String queryString = mapToQueryString(queryData);

        //请求体
        String requestId = UUID.randomUUID().toString();
        Map<String, Object> data = new HashMap<>();
        data.put("task_id", "fb16d23843175f7f8c676ec14b502867");
        data.put("businessCode", "pc");
        data.put("dataId", requestId);
        //将请求体转为JSON
        String string = JSON.toJSONString(data);

        HttpHeaders headers = VivoAuth.generateAuthHeaders(APP_ID, APP_KEY, METHOD, URI, queryString);
        String url = String.format("http://%s%s", DOMAIN, URI,queryString);
        headers.add("Content-Type", "application/json");
        RestTemplate restTemplate = new RestTemplate();
        return getString(url, string, restTemplate, headers);
    }




    // 文本向量
    @GetMapping("/predict")
    public String embedding() throws UnsupportedEncodingException, JsonProcessingException {
        final String APP_ID =  "3032693269";
        final String APP_KEY ="pORdeLuUVXfBNIeY";
        final String DOMAIN = "api-ai.vivo.com.cn";
        final String URI = "/embedding-model-api/predict/batch";
        final String METHOD = "POST";

        // 定义请求体数据
        Map<String, Object> data = new HashMap<>();
        data.put("model_name", "m3e-base");
        data.put("sentences", new String[]{"豫章故郡，洪都新府", "星分翼轸，地接衡庐"});

        Map<String, Object> params = new HashMap<>();
        String queryString = mapToQueryString(params);

        HttpHeaders headers = VivoAuth.generateAuthHeaders(APP_ID, APP_KEY, METHOD, URI, queryString);
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        Map<String, String> headersMap = headers.toSingleValueMap();
        // 将 Map 转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonHeaders = objectMapper.writeValueAsString(headersMap);
        System.out.println(jsonHeaders);

        String url = String.format("http://%s%s", DOMAIN, URI);
        String requsetBodyString = new ObjectMapper().writeValueAsString(data);
        RestTemplate restTemplate = new RestTemplate();
        return getString(url, requsetBodyString, restTemplate, headers);
    }

    //文本翻译
    @GetMapping("/translation")
    public String translation(@RequestParam String prompt) throws UnsupportedEncodingException {
        final String APP_ID =  "3032693269";
        final String APP_KEY ="pORdeLuUVXfBNIeY";
        final String METHOD = "POST";   System.err.println(prompt);
        final String URI = "/translation/query/self";
        final String DOMAIN = "api-ai.vivo.com.cn";
        String requestId = UUID.randomUUID().toString();
        Map<String, Object> data = new HashMap<>();
        data.put("from", "zh-CHS");
        data.put("to", "en");
        data.put("text", prompt);

        data.put("app", "test");
        data.put("requestId", requestId);
        Map<String, Object> params = new HashMap<>();
        String queryString = mapToQueryString(params);
        // 生成签名头部
        HttpHeaders headers = VivoAuth.generateAuthHeaders(APP_ID, APP_KEY, METHOD, URI, queryString);
        // 添加请求头部
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        String url = String.format("http://%s%s", DOMAIN, URI);
        // 构建请求体
        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            requestBody.add(entry.getKey(), (String) entry.getValue());
        }
        // 发送 HTTP 请求
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.addAll(headers);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestBody, httpHeaders);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            System.out.println("Response body: " + response.getBody());
        } else {
            System.out.println("Error response: " + response.getStatusCode());
        }
        return response.getBody();
    }
    @GetMapping("/translationAuto")
    public String processVivogptRequest(@RequestParam String prompt, @RequestParam String origin, @RequestParam String target) throws UnsupportedEncodingException {
        final String APP_ID =  "3032693269";
        final String APP_KEY ="pORdeLuUVXfBNIeY";
        final String METHOD = "POST";
        final String URI = "/translation/query/self";
        final String DOMAIN = "api-ai.vivo.com.cn";
        System.err.println(prompt);
        System.err.println(origin);
        System.err.println(target);
        String requestId = UUID.randomUUID().toString();
        Map<String, Object> data = new HashMap<>();
        data.put("from", origin);
        data.put("to", target);
        data.put("text", prompt);

        data.put("app", "test");
        data.put("requestId", requestId);
        Map<String, Object> params = new HashMap<>();
        String queryString = mapToQueryString(params);
        // 生成签名头部
        HttpHeaders headers = VivoAuth.generateAuthHeaders(APP_ID, APP_KEY, METHOD, URI, queryString);
        // 添加请求头部
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        String url = String.format("http://%s%s", DOMAIN, URI);
        // 构建请求体
        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            requestBody.add(entry.getKey(), (String) entry.getValue());
        }
        // 发送 HTTP 请求
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.addAll(headers);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestBody, httpHeaders);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            System.out.println("Response body: " + response.getBody());
        } else {
            System.out.println("Error response: " + response.getStatusCode());
        }
        return response.getBody();
    }


    // 将请求参数转为 查询url
    public static String mapToQueryString(Map<String, Object> map) {
        if (map.isEmpty()) {
            return "";
        }
        StringBuilder queryStringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (!queryStringBuilder.isEmpty()) {
                queryStringBuilder.append("&");
            }
            queryStringBuilder.append(entry.getKey());
            queryStringBuilder.append("=");
            queryStringBuilder.append(entry.getValue());
        }
        return queryStringBuilder.toString();
    }


    // 加载图片并进行base64编码
    public String loadImageAsBase64(String imagePath) {
        try {
            // 读取图像文件并转换为字节数组
            Path path = Paths.get(new ClassPathResource(imagePath).getURI());
            byte[] imageBytes = Files.readAllBytes(path);

            // 将字节数组转换为Base64编码的字符串
            return Base64.getEncoder().encodeToString(imageBytes);
        } catch (IOException e) {
            throw new RuntimeException("无法加载或读取资源文件：" + imagePath, e);
        }
    }

}
